package com.ocom.nettyxf.service.impl;

import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.IPUtils;
import com.ocom.common.utils.NumConvertUtil;
import com.ocom.nettyxf.client.AiotFeignService;
import com.ocom.nettyxf.client.PayHandleFeignService;
import com.ocom.nettyxf.ropo.TcpServiceRopo;
import com.ocom.nettyxf.service.MachTcpService;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;


@Slf4j
@Service
@Resource
public class MachTcpServiceImpl implements MachTcpService {


    @Autowired
    private PayHandleFeignService payHandleFeignService;

    @Autowired
    private AiotFeignService aiotFeignService;

    @Resource
    RedisUtil redisUtil;

    //签到 (0x0001)
    @Override
    public byte[] sign(TcpServiceRopo tcpServiceRopo) throws Exception {
        //固件版本
        String GJlen = tcpServiceRopo.getCommandParam().substring(12, 14);
        Integer len = NumConvertUtil.HexStringToInt(GJlen);
        String ues3 = tcpServiceRopo.getCommandParam().substring(14, 14+len*2);

        ues3 = NumConvertUtil.hexStringToString(ues3);

        //要返回的对象
        TcpServiceRopo resp = new TcpServiceRopo();

        //赋返回值  全是16进制字符串
        resp.setMachId(tcpServiceRopo.getMachId());
        resp.setEdition(tcpServiceRopo.getEdition());
        resp.setType(tcpServiceRopo.getType());
        resp.setPackageNum(tcpServiceRopo.getPackageNum());
        resp.setCommandType(tcpServiceRopo.getCommandType());


        //响应写死
        resp.setRespTip("02");
        //随机 sessionid
        Random rand = new Random();
        StringBuilder session = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            Integer j = rand.nextInt(254);
            session.append(NumConvertUtil.IntToHexStringNum(j++, 2));
        }
        resp.setSessionId(session.toString());

        redisUtil.hmSet("tcpXfMach:" + tcpServiceRopo.getMachId(), "ip", IPUtils.getLocalIp());

        redisUtil.hmSet("tcpXfMach:" + tcpServiceRopo.getMachId(), "sessionId", session.toString());

        //获取企业Id
        //机器号
        String machno = (String) tcpServiceRopo.getMachId();
        RespMachMessage respMachMessage = aiotFeignService.getDeviceState(machno);
        if (!respMachMessage.getCode().equals("0000")) {
            log.info("签到失败，未找到单位  【{}】【{}】 ", tcpServiceRopo, respMachMessage);
            resp.setCommandParam("0003",4,"签到失败，未找到单位");
            String rc = resp.getHexStr();
            log.info("Tcp 签到失败  参数【{}】 响应【{}】 ，【{}】",tcpServiceRopo,resp,rc);
            return HexUtil.decodeHex(rc);
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(respMachMessage.getData()));

        //获取单位编号
        Integer companyId = jsonObject.getInteger("companyId");
        Integer saasNo = jsonObject.getInteger("saasNo");
        redisUtil.hmSet("tcpXfMach:" + tcpServiceRopo.getMachId(), "saasNo", saasNo);
        redisUtil.hmSet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId", companyId);

        //响应结果  23个字节
        String param = "00001111111122222222222200000000000000FF010000";

        //系统时间
        Date now = new Date();
        String sysDate = DateFormatUtils.format(now, "YMMddHHmmss").substring(2);
        StringBuilder stringBuilder = new StringBuilder(param);
        stringBuilder.replace(12, 24, sysDate);

        stringBuilder.replace(4, 12, resp.getSessionId());

        //平台编号为1按照本平台走
        if (saasNo == 1) {
            RespMachMessage resGetDeviceFlag = aiotFeignService.getDeviceFlag(machno, ues3);
            if (!resGetDeviceFlag.getCode().equals("0000")) {
                resp.setCommandParam("0003",4,"SaasNo非本平台");
                String rc = resp.getHexStr();
                log.info("Tcp 签到失败  参数【{}】 响应【{}】 ，【{}】",tcpServiceRopo,resp,rc);
                return HexUtil.decodeHex(rc);
            }
            JSONObject jsonGetDeviceFlag = JSON.parseObject(JSON.toJSONString(resGetDeviceFlag.getData()));

            try {
                Result result = payHandleFeignService.GetMerchInfoByMachNo(companyId.longValue(), machno);
                log.info("tcp设备签到  【QYRfMm0F】  -获取商户名称- 【{}】", result);
                if (result.getCode() == 200) {
                    JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(result.getData()));
                    String merchName = jsonObject1.getString("merchName");
                    String mer = NumConvertUtil.toGBK(merchName);
                    Integer size = mer.length() / 2;
                    String sizeNum = NumConvertUtil.IntToHexStringNum(size, 2);
                    stringBuilder.replace(42, 46, sizeNum);
                    stringBuilder.append(mer);
                }
            } catch (Exception e) {
                log.info("Tcp 获取商户名称异常【{}】" ,e);
            }

            if (jsonGetDeviceFlag.getInteger("firmwareUpdate") == 1) {
                stringBuilder.replace(24, 26, "01");
            }
            resp.setCommandParam(stringBuilder.toString());
            String rc = resp.getHexStr();
            log.info("Tcp 签到成功  参数【{}】 响应【{}】 ，【{}】",tcpServiceRopo,resp,rc);
            return HexUtil.decodeHex(rc);
        }

        log.info("xf机器saasNo未配置 【{}】 ", tcpServiceRopo);
        resp.setCommandParam("0001",4,"xf机器saasNo未配置");
        String rc = resp.getHexStr();
        log.info("签到返回 【{}】 ", rc);
        return HexUtil.decodeHex(rc);
    }



}
